//
//  AccountViewController.m
//  Leo01
//
//  Created by 张旭 on 15/9/3.
//  Copyright (c) 2015年 张旭. All rights reserved.
//

#import "AccountViewController.h"
#import "BugReportDetailsViewController.h"
#import "VersionViewController.h"

#import "LeoMsg.h"
#import "DataManager.h"
#import "SyncManager.h"
#import "DateViewController.h"
#import "SetTextViewController.h"

#import "AppDelegate.h"
#import "SyncManager.h"
#import "DataManager.h"
#import "LoginViewController.h"
@interface AccountViewController ()
@property (nonatomic,retain) SyncManager *syncManager;
@property (nonatomic,retain) DataManager *dataManager;
@property(nonatomic,strong) UIActionSheet *actionSheet;
@property(nonatomic,strong) UIImagePickerController *picker;
@property(nonatomic,strong) NSString *photoUrl;
@property(nonatomic,strong) NSString *photoName;
@property(nonatomic,weak) AppDelegate *mydelegate;


@end

@implementation AccountViewController
@synthesize navLeftButton;
@synthesize headImg;
@synthesize headImgView;
@synthesize nicknameLabel;
@synthesize birthLabel;
@synthesize birthView;
@synthesize nicknameView;
@synthesize accountPhoneLabel;
@synthesize logoutButton;
@synthesize mydelegate;
@synthesize originalView;
@synthesize scroll;
int visitedOrNot=0;
//@synthesize scroll;
-(void)dealloc
{
    self.syncManager=NULL;
    self.dataManager=NULL;
    self.actionSheet=NULL;
    self.picker=NULL;
    self.photoUrl=NULL;
    self.photoName=NULL;
    mydelegate=NULL;
}
//复制UIVIEW
- (UIView*)duplicate:(UIView*)view
{
    NSData * tempArchive = [NSKeyedArchiver archivedDataWithRootObject:view];
    return [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];
}
-(void)viewWillDisappear:(BOOL)animated
{

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
        if (scrollView.contentOffset.y <0 ) {
            scrollView.contentOffset = CGPointMake(0, 0);
            return;
    }  
    return;  
}
-(void)viewWillLayoutSubviews{
//    float width=[UIScreen mainScreen].bounds.size.width;
//    float height=[UIScreen mainScreen].bounds.size.height;
//    originalView.frame = CGRectMake(0, -64, width, 667);
//    //self.view=originalView;
}
-(void)viewWillAppear:(BOOL)animated{
    
    visitedOrNot=visitedOrNot+1;
    //originalView=[self duplicate:self.view];
    //[self viewWillLayoutSubviews];
    float width=[UIScreen mainScreen].bounds.size.width;
    float height=[UIScreen mainScreen].bounds.size.height;
    originalView.frame = CGRectMake(0, 0, width, 667);
    
    scroll=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, width, height-40-88)];
    scroll.delegate=self;
    
    scroll.contentSize=CGSizeMake(width, 667-40-88);
    
    
    if (visitedOrNot==1){
        scroll.contentInset=UIEdgeInsetsMake(-64, 0, 64, 0);
    }
    else{
        scroll.contentInset=UIEdgeInsetsMake(0, 0, 0, 0);
    }

    NSLog(@"宽度是%f",height);
    //UIView *newView=[self duplicate:self.view];
    //newView.frame=CGRectMake(0, 0, width, 750);
    //originalView.frame = CGRectMake(0, 64, width, 750);
    [scroll addSubview:originalView];
    
    self.view=scroll;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    originalView=self.view;
    visitedOrNot=0;
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.title=@"账号";
    mydelegate=[[UIApplication sharedApplication] delegate];
    /*
    if(mydelegate.isAdmin==YES)
    {
        [self initViewActions];
        [self beforeCamara];
    }
    else
    {
        self.imgNext.hidden=YES;
        self.nickNext.hidden=YES;
        self.birthNext.hidden=YES;
    }*/
    [self initViewActions];
    [self beforeCamara];
    [self initDataProxy];
    [self getAccountData];

    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}

- (void)initViewActions{
    UITapGestureRecognizer *tapReconizerToBugReport = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toBugReport)];
    [self.bugReportView addGestureRecognizer:tapReconizerToBugReport];
    
    UITapGestureRecognizer *tapReconizerToVersion = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toVersion)];
    [self.versionView addGestureRecognizer:tapReconizerToVersion];
    
    UITapGestureRecognizer *tapReconizerToSetImage = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(setImg)];
    [self.headImgView addGestureRecognizer:tapReconizerToSetImage];
    
    UITapGestureRecognizer *tapReconizerToBirth = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(BirthAction)];
    [self.birthView addGestureRecognizer:tapReconizerToBirth];
    
    UITapGestureRecognizer *tapReconizerToName = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(nameAction)];
    [self.nicknameView addGestureRecognizer:tapReconizerToName];
    
}

- (void)toBugReport{
    BugReportDetailsViewController *bugReportViewController = [[BugReportDetailsViewController alloc]init];
    //[self.navigationController pushViewController:accountViewController animated:YES];
    [self.navigationController pushViewController:bugReportViewController animated:YES];
}

- (void)toVersion{
    VersionViewController *versionViewController = [[VersionViewController alloc]init];
    [self.navigationController pushViewController:versionViewController animated:YES];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)initDataProxy{
    self.syncManager=[[SyncManager alloc] init];
    self.dataManager=[[DataManager alloc] init];
}
-(void)getAccountData{
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.silentDetailsDataArray = [[NSMutableArray alloc]init];
    
    //User *user=[User sharedSingleton];
    User *user=[self.dataManager getActiveUser];
    if(user==NULL)
        return;
    Manager *manager=[self.dataManager getManagerByUid:user.uid];
    if(user.nickName!=NULL&&![user.nickName isEqualToString:@"(null)"])
    {
        nicknameLabel.text=user.nickName;
    }
    else
    {
        if(manager!=NULL&& manager.nickName!=NULL&&![manager.nickName isEqualToString:@"(null)"])
        {
            nicknameLabel.text=manager.nickName;
            user.nickName=manager.nickName;
        }
    }
    if(user.birth!=NULL&&[user.birth length]>0&&![user.birth isEqualToString:@""])
    {
        birthLabel.text=[Tooler second2Stringformat:user.birth withFormatter:@"yyyy-MM-dd"];
    }
    else
    {
        if(manager!=NULL&&manager.birth!=NULL&&![manager.birth isEqualToString:@"(null)"])
        {
            birthLabel.text=[Tooler second2Stringformat:manager.birth withFormatter:@"yyyy-MM-dd"];
            user.birth=manager.birth;
        }
    }
    if(user.account!=NULL&&![user.account isEqualToString:@"(null)"])
    {
        accountPhoneLabel.text=user.account;
    }
    headImg.layer.cornerRadius = headImg.frame.size.width / 2;
    headImg.clipsToBounds = YES;
        if(user.pic_url!=NULL&&![user.pic_url isEqualToString:@"(null)"]&&![user.pic_url isEqualToString:@""])
    {
        NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],user.pic_url];
        headImg.image=[UIImage imageWithContentsOfFile:headUrl];
    }
    else
    {
        if(manager!=NULL&&manager.pic_url!=NULL&&![manager.pic_url isEqualToString:@"(null)"]&&![manager.pic_url isEqualToString:@""])
        {
            NSString *headUrl=[NSString stringWithFormat:@"%@%@",[Tooler getDocumentDirectory],manager.pic_url];
            headImg.image=[UIImage imageWithContentsOfFile:headUrl];
            user.pic_url=manager.pic_url;
        }
        else
        {
            headImg.image=[UIImage imageNamed:@"avater_man.png"];
        }
        
    }
}
-(void)initAccountData
{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
-(void)nameAction
{
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
     SetTextViewController *nameVC=[[SetTextViewController alloc]init];
    //
    nameVC.motherWindow=alertView;
    nameVC.motherLabel=self.nicknameLabel;
    nameVC.type=1;
    if(nicknameLabel.text!=NULL&&![nicknameLabel.text isEqualToString:@"(null)"])
    {
        nameVC.initialString=nicknameLabel.text;
    }
    alertView.rootViewController=nameVC;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];

}
-(void)BirthAction
{
    UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
    UIWindow *alertView=[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //
    DateViewController *date=[[DateViewController alloc]init];
    //
    date.originalBirth=birthLabel.text;
    [date setMotherWindow:alertView];
    [date setMotherLabel:birthLabel];
    date.type=1;
    alertView.rootViewController=date;
    [keyWindow addSubview:alertView];
    [alertView setWindowLevel:UIWindowLevelAlert];
    [alertView makeKeyAndVisible];
    
}

//相机相册部分
- (void)setImg{
    [self.actionSheet showInView:self.view];
    
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self camera];
    }else if (buttonIndex == 1) {
        [self LocalPhoto];
    }else if(buttonIndex == 2) {
        
    }
    
}
-(void)beforeCamara
{
    self.actionSheet = [[UIActionSheet alloc]
                        initWithTitle:nil
                        delegate:self
                        cancelButtonTitle:nil
                        destructiveButtonTitle:nil
                        otherButtonTitles:@"拍照", @"从手机相册选择",@"取消",nil];
    self.actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    self.picker = [[UIImagePickerController alloc] init];
    self.picker.delegate = self;
    //设置选择后的图片可被编辑
    self.picker.allowsEditing = YES;
    
    self.picker.navigationBar.translucent =NO;
    
    [self.picker.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    [self.picker.navigationBar setBarTintColor:[UIColor colorWithRed:71/255.0 green:178/255.0 blue:247/255.0 alpha:1.0]];
}

-(void)LocalPhoto
{
    self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    //[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
-(void)camera
{
    self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
   // [[UINavigationBar appearance] setTintColor:[UIColor blackColor]];
    [self presentViewController:self.picker animated:YES completion:nil];
}
//取消选择
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData *data=UIImageJPEGRepresentation(image, 0.3);
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [[Tooler getDocumentDirectory] stringByAppendingString:@"/headimg"];
        if([Tooler isDirectoryExist:DocumentsPath])
        {
            NSString *ts=[Tooler getTS];
            self.photoName=[NSString stringWithFormat:@"/headimg/image%@.jpg",ts];
            //得到选择后沙盒中图片的完整路径
            self.photoUrl = [[NSString alloc]initWithFormat:@"%@/image%@.jpg",DocumentsPath,ts];
            NSError *error;
            [data writeToFile:self.photoUrl options:NSDataWritingFileProtectionComplete error:&error];
            if(error==NULL)
            {
                self.headImg.image=[UIImage imageNamed:self.photoUrl];
                User *user=[User sharedSingleton];
                if(user==NULL)
                    return;
                user.photoName=self.photoName;
                user.pic_url=self.photoName;
                user.full_url=self.photoUrl;
                [self.syncManager setUserInfo:^(SyncResult result, NSDictionary *retValue, NSString *description) {
                    if(result==SUCESS)
                    {
                        [LeoMsg showMsg:@"头像修改成功"];
                    }
                    else
                    {
                        [Tooler showHttpMsg:result description:description msg:@"设置用户信息失败"];
                    }
                }];
            }
            
        }
        [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [self.picker dismissViewControllerAnimated:YES completion:nil];
        
    }
    
}


- (IBAction)logout:(id)sender {
    [self.syncManager phoneLogout:^(SyncResult result, NSDictionary *retValue, NSString *description) {
       if(result==SUCESS)
       {
           User *user=[User sharedSingleton];
           if(user==NULL||user.uid==NULL)
           {
               [self logoutAction];
               return ;
           }
           [Tooler updateAccountName:user.account];
           BOOL res=[self.dataManager logoutUser:user];
           if(res)
           {
               
               [User logout];
               [self logoutAction];
               
           }
           else
           {
               [LeoMsg showMsg:@"程序发生错误，code is 1"];
           }
       }
       else
       {
           [Tooler showHttpMsg:result description:description msg:@"退出登录失败"];
       }
    }];

}


-(void)logoutAction
{
    
    LoginViewController *LoginView=[[LoginViewController alloc] init];
    UINavigationController *LoginNavigationController = [[UINavigationController alloc] initWithRootViewController:LoginView];
    if(mydelegate!=NULL){
        [mydelegate setNavProperty:LoginNavigationController];
        mydelegate.location_sync = NO;
        mydelegate.chat_sync=NO;
        mydelegate.growth_sync=NO;
        mydelegate.manager_sync=NO;
        [mydelegate disconnectToTcp];
    }
    self.view.window.rootViewController = LoginNavigationController;
    LoginView=NULL;
    [self.navigationController popToRootViewControllerAnimated:YES];
}
@end
